package com.mmall.util;

import com.google.common.collect.Lists;
import com.mmall.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.List;

public class JsonUtil {

    private static Logger log = LoggerFactory.getLogger(JsonUtil.class);
    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        //对象所有字段全部列入
        objectMapper.setSerializationInclusion(Inclusion.ALWAYS);
        //取消默认转换timestamps格式
        objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
        //忽略空json转换错误
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);

        //所有日期格式统一为以下格式 yyyy-MM-dd HH:mm:ss
        objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT));

        //忽略在json中存在,但是在java bean中不存在的错误
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static <T> String objToString(T obj) {
        if (obj == null) {
            return null;
        }

        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (Exception e) {

            log.warn("obj to string is error", e);
            e.printStackTrace();
            return null;

        }
    }

    public static <T> String objToStringtPretty(T obj) {
        if (obj == null) {
            return null;
        }

        try {
            return obj instanceof String ? (String) obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (Exception e) {

            log.warn("obj to string is error", e);
            e.printStackTrace();
            return null;

        }
    }

    public static <T> T strToObj(String str, Class<T> tClass) {
        if (StringUtils.isEmpty(str) || tClass == null) {
            return null;
        }

        try {
            return tClass.equals(String.class) ? (T) str : objectMapper.readValue(str, tClass);
        } catch (Exception e) {
            log.warn("str to obj is error", e);
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T strToObj(String str, TypeReference<T> typeReference) {
        if (StringUtils.isEmpty(str) || typeReference == null) {
            return null;
        }
        try {
            return (T) (typeReference.getType().equals(String.class) ? str : objectMapper.readValue(str, typeReference));
        } catch (Exception e) {
            log.warn("obj to str is error", e);
            e.printStackTrace();
            return null;
        }

    }

    public static <T> T strToObj(String str, Class<?> collectionClass, Class<?>... elementClass) {
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClass);

        try {
            return objectMapper.readValue(str, javaType);
        } catch (Exception e) {
            log.warn("obj to str is error", e);
            e.printStackTrace();
            return null;
        }

    }


    public static void main(String[] args) {
        User user = new User();
        user.setId(1);
        user.setPassword("1234560");
        String result = objToString(user);
        log.info("user:{}", result);

        log.info("反序列化{}", strToObj(result, User.class).getPassword());
        User user1 = new User();
        user1.setPassword("12546541864@sadas.cni");
        user1.setAnswer("adasdawda大胆的技能");
        List<User> userList = Lists.newArrayList();
        userList.add(user);
        userList.add(user1);
        result = objToStringtPretty(userList);
        log.info("userlist:{}", result);
        List<User> userList1 = strToObj(result, new TypeReference<List<User>>() {
        });
        System.out.println(userList1);
        System.out.println(strToObj(result, List.class, User.class));


    }
}
